package com.cxyd.common.config;

import com.cxyd.common.interceptor.CustomHeaderInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Collections;

@Configuration
public class RestTemplateConfig {

    @Autowired
    private CustomHeaderInterceptor customHeaderInterceptor;

    /**
     * http连接管理器
     *
     * @return
     */
    @Bean
    public HttpClientConnectionManager poolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        //最大连接数
        httpClientConnectionManager.setMaxTotal(500);
        //同路由并发数
        httpClientConnectionManager.setDefaultMaxPerRoute(100);
        return httpClientConnectionManager;
    }

    @Bean
    public HttpClient httpClient(HttpClientConnectionManager poolingHttpClientConnectionManager) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //设置http连接管理器
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

        //设置默认请求头
        return httpClientBuilder.build();
    }

    /**
     * 请求连接池配置
     *
     * @param httpClient
     * @return
     */
    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        //httpClient创建器
        clientHttpRequestFactory.setHttpClient(httpClient);
        //连接超时时间
        clientHttpRequestFactory.setConnectTimeout(5 * 1000);
        //数据读取超时时间
        clientHttpRequestFactory.setReadTimeout(10 * 6000);
        //连接池获取请求连接的超时时间
        clientHttpRequestFactory.setConnectionRequestTimeout(10 * 1000);
        return clientHttpRequestFactory;
    }

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
        //boot中可使用RestTemplateBuilder.build创建
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        return restTemplate;
    }

    // 新的RestTemplate Bean（用于跳过SSL验证的HTTPS请求）
    @Bean("sslIgnoreRestTemplate")
    public RestTemplate sslIgnoreRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        // 创建信任所有证书的策略
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        // 创建SSL上下文
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        // 创建SSL连接工厂
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // 创建HTTP客户端
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        // 创建请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        // 创建并配置RestTemplate
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 添加自定义请求头拦截器
        restTemplate.setInterceptors(Collections.singletonList(customHeaderInterceptor));

        // 创建并返回RestTemplate
        return restTemplate;
    }
}
